package com.cloud.core.http.error;

import android.net.ParseException;
import android.text.TextUtils;
import android.util.Log;

import com.cloud.core.BuildConfig;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;


/**
 * Created by Chen on 2017/6/19.
 * 功能描述：
 */

public class ExceptionEngine {

    public static ApiException handleException(Throwable e) {

        ApiException ex;
        //HTTP错误
        if (e instanceof retrofit2.HttpException) {
            ex = new ApiException(e, ERROR.HTTP_ERROR);
            ex.message = "网络错误，请检查网络";
            return ex;
        } else if (e instanceof NoRouteToHostException || e instanceof UnknownHostException) {
            ex = new ApiException(e, ERROR.HTTP_ERROR);
            ex.message = "网络错误，请检查网络";
            return ex;
            //连接超时错误
        } else if (e instanceof SocketTimeoutException) {
            ex = new ApiException(e, ERROR.HTTP_ERROR);
            ex.message = "连接超时,请稍后重试";
            return ex;
        } else if (e instanceof AppException) {
            AppException resultException = (AppException) e;
            ex = new ApiException(resultException, resultException.code);
            ex.message = resultException.message;
            return ex;
        } else if (e instanceof JSONException
                || e instanceof JsonParseException
                || e instanceof ParseException) {
            ex = new ApiException(e, ERROR.PARSE_ERROR);
            //均视为解析错误
            ex.message = "服务器返回数据格式异常";
            return ex;
        } else if (e instanceof SocketException) {
            ex = new ApiException(e, ERROR.NETWORD_ERROR);
            //均视为网络错误
            ex.message = "网络错误，请检查网络";
            return ex;
        } else if (e instanceof ApiException) {
            return ((ApiException) e);
        } else {
            if (BuildConfig.DEBUG) {
                e.printStackTrace();
            }
            if (!TextUtils.isEmpty(e.getMessage()))
                Log.e("error", e.getMessage());
            ex = new ApiException(e, ERROR.UNKNOWN);
            ex.message = "出现异常，请联系管理员";
            return ex;
        }
    }
}
